package log

import (
	"fmt"
	"gitee.com/scottq/go-framework/src/v1/config"
	"io"
	"time"
)

// 指定writer的日志打印
type writerLog struct {
	w          io.Writer
	level      int
	callerSkip int

	cnf *config.LogConfig

	logHelper
}

func NewWriterLog(w io.Writer, level int, cs ...*config.LogConfig) *writerLog {
	c := config.DefiLogConfig()
	if len(cs) > 0 && cs[0] != nil {
		c = cs[0]
	}

	l := &writerLog{
		w:          w,
		level:      level,
		cnf:        c,
		callerSkip: 3,
	}

	l.callerSkip += l.lCallerSkip(c)

	return l
}

func (l *writerLog) Debug(format string, params ...interface{}) {
	l.logItem(DebugLog, format, params...)
}

func (l *writerLog) Info(format string, params ...interface{}) {
	l.logItem(InfoLog, format, params...)
}

func (l *writerLog) Warn(format string, params ...interface{}) {
	l.logItem(WarnLog, format, params...)
}

func (l *writerLog) Error(format string, params ...interface{}) {
	l.logItem(ErrorLog, format, params...)
}

func (l *writerLog) Panic(format string, params ...interface{}) {
	l.logItem(PanicLog, format, params...)
}

func (l *writerLog) Fatal(format string, params ...interface{}) {
	l.logItem(FatalLog, format, params...)
}

func (l *writerLog) logItem(level int, format string, params ...interface{}) {
	if level < l.level {
		return
	}
	if l.w == nil {
		return
	}
	if len(params) > 0 {
		format = fmt.Sprintf(format, params...)
	}

	a := fmt.Sprintf("[%s] %s %s %s\n",
		LevelMap[level],
		time.Now().Format(time.RFC3339),
		l.lFilepath(l.cnf, l.callerSkip),
		format,
	)
	l.w.Write([]byte(a))
}

func (l *writerLog) Write(p []byte) (n int, err error) {
	return l.w.Write(p)
}

func (l *writerLog) Ctl(t bool) ILog {
	if !t {
		return _nullLog
	}
	return l
}

func (l *writerLog) Caller(skip int) ILog {
	nl := &(*l)
	nl.callerSkip += skip
	return nl
}
